<?php

namespace app\api\controller;

use app\admin\model\Levels;
use app\admin\model\Mail;
use app\admin\model\Tables;
use app\api\model\Lineup;
use app\api\model\Order;
use app\common\controller\Api;
use app\common\model\ScoreLog;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Log;
use function fast\e;

/**
 * 员工端
 */
class Staff extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    /**
     * 消费金额赠送积分
     * @ApiMethod (POST)
     * @ApiParams   (name="money", type="string", required=true, description="金额")
     * @ApiParams   (name="user_id", type="string", required=true, description="用户id")
     */
    public function send_score()
    {

        $money = input('post.money');
        $user_id = input('post.user_id');
        if (!$money || !$user_id) {
            $this->error('An error has occurred. Please report this issue to customer service.');
        }
        $money_score = config('site.money_score');
        $score = round($money * $money_score);
        //用户增加积分及积分记录
        $user = User::where(['id' => $user_id])->find();
        if (!$user) {
            $this->error('An error has occurred. Please report this issue to customer service.');
        }
        $start_time = strtotime(date('Y-m-d'));
        $end_time = $start_time + 86399;
        Log::write('score_recharge:'.$user_id);
        if (ScoreLog::where('user_id', $user_id)->where('createtime', 'between time', [$start_time, $end_time])
                ->where('status',ScoreLog::STATUS_XF)->count()
            >= 3) {
            $this->error('You can’t earn more rewards today.');
        }


        Db::startTrans();
        try {
            $before = $user['score'];
            $end_score = $user['score'] + $score;
            $user->score = $end_score;
            $log_id = ScoreLog::insertGetId([
                'user_id' => $user_id,
                'score' => $score,
                'before' => $before,
                'after' => $end_score,
                'memo' => 'Reward Points',
                'status' => ScoreLog::STATUS_XF,
                'createtime' => time(),
                'staff_id'=>$this->auth->id
            ]);
            //发送站内信
            Mail::create([
                'title' => 'Points Earned',
                'content' => 'You’ve earned ' . $score . ' points! Thank you for coming on 
                [' . date('F j, Y \a\t g:i A', time()) . ']. Your reward has been added to your account.',
                'user_id' => $user_id,
                'type' => 1,
                'page_type' => 0,
                'jump' => 0,
                'shop_id' => 1,
            ]);
            //会员升级
            $end_consumption_amount = $user['consumption_amount'] + $money;
            $user->consumption_amount = $end_consumption_amount;
//        $level_message=Levels::all();
//        $level=0;
//        foreach ($level_message as $value){
//            if($end_consumption_amount>$value['min_money']){
//                $level=$value['id'];
//            }
//        }
//        $user->level=$level;
            $user->save();

            (new User())->upLevel($user_id);  //会员升级

            Db::commit();
        } catch (Exception $exception) {
            Db::rollback();
            $this->error($exception->getMessage());
        }

        $this->success('成功', ['log_id' => $log_id]);
    }


    /**
     * Notes: 撤销 积分
     * User: chenLei
     * Date: 9/17/25
     */
    public function cancelScore()
    {
        $log_id = input('log_id');
        if (empty($log_id)) {
            $this->error('Log id error');
        }

        $scoreLogModel = new ScoreLog();
        $res = $scoreLogModel->cancelScore($log_id,$this->auth->id);

        if ($res === false) {
            $this->error($scoreLogModel->getError());
        }

        $this->success('success');


    }


    /**
     * 核销兑换订单
     * @ApiMethod (POST)
     * @ApiParams   (name="order_sn", type="string", required=true, description="订单号")
     */
    public function wait_off_order()
    {
        $order_sn = input('post.order_sn');
        $res = Order::where(['order_sn' => $order_sn, 'is_use' => 0])->find();
        if (!$res) {
            $this->error('Order does not exist');
        }
        $res->is_use = 1;
        $res->use_time = time();
        $res->save();
        $this->success('成功', ['order_id' => $res['id']]);
    }

    /**
     * Notes: 撤销 核销
     * User: chenLei
     * Date: 9/17/25
     */
    public function cancelVerificationOrder()
    {
        $order_id = input('order_id');
        if (empty($order_id)) {
            $this->error('Order id error');
        }

        $orderModel = new Order();
        $res = $orderModel->cancelVerificationOrder($order_id);
        if ($res === false) {
            $this->error($orderModel->getError());
        }

        $this->success('success');
    }

    /**
     * 桌子
     */
    public function tables()
    {
        $shop_id = $this->request->header('shopid', 1);
        $res = Tables::where(['shop_id' => $shop_id])->order('max_num asc')->select();
        $this->success('成功', $res);
    }

    /**
     * 排队信息
     * @ApiMethod (POST)
     * @ApiParams   (name="table_id", type="string", required=true, description="桌子ID")
     * @ApiReturnParams   (name="shop_name", type="text", required=true, description="店铺名称")
     * @ApiReturnParams   (name="status", type="text", required=true, description="1等待中2成功0失败")
     * @ApiReturnParams   (name="ranking", type="text", required=true, description="排名")
     * @ApiReturnParams   (name="table_message", type="text", required=true, description="桌子信息")
     */
    public function line_up_message()
    {
        $shop_id = $this->request->header('shopid', 1);
        $table_id = input('post.table_id');
        $res = Lineup::where(['table_id' => $table_id, 'status' => 1, 'shop_id' => $shop_id])->order('ranking')->select();
        foreach ($res as &$value) {
            $value['table_message'] = Tables::where(['id' => $value['table_id']])->find();
            $value['table_code'] = $value['table_message']['name'] . $value['id'];
            $value['user_info'] = User::where(['id' => $value['user_id']])->find();
        }
        $this->success('成功', $res);
    }

    /**
     * 删除排队信息
     * @ApiMethod (POST)
     * @ApiParams   (name="id", type="string", required=true, description="id")
     */
    public function del_line_up()
    {
        $id = input('post.id');
        $res = Lineup::where(['id' => $id])->find();
        //后面的排队信息变化
        $line_up = Lineup::where(['table_id' => $res['table_id'], 'shop_id' => $res['shop_id'], 'ranking' => ['>', $res['ranking']]])->select();
        foreach ($line_up as &$value) {
            $value->ranking = $value['ranking'] - 1;
            $value->save();
        }
        $res->delete();
        $this->success('成功');
    }

    /**
     * 排队确认成功
     * @ApiMethod (POST)
     * @ApiParams   (name="id", type="string", required=true, description="id")
     */
    public function success_lineup()
    {
        $id = input('post.id');
        $res = Lineup::where(['id' => $id])->find();
        //后面的排队信息变化
        $line_up = Lineup::where(['table_id' => $res['table_id'], 'shop_id' => $res['shop_id'], 'ranking' => ['>', $res['ranking']]])->select();
        foreach ($line_up as &$value) {
            $value->ranking = $value['ranking'] - 1;
            $value->save();
        }
        //发送站内信
        Mail::create([
            'title' => 'Queue Called',
            'content' => 'Your queue number has been called. Please proceed to the counter or pickup point within 5minutes.Time: ' . date('F j, Y \a\t g:i A', time()),
            'user_id' => $res['user_id'],
            'type' => 1,
            'page_type' => 0,
            'jump' => 0,
            'shop_id' => 1,
        ]);
        $res->status = 2;
        $res->save();
        $this->success('成功');
    }

    /**
     * 排队过号
     * @ApiMethod (POST)
     * @ApiParams   (name="id", type="string", required=true, description="id")
     */
    public function pass_lineup()
    {
        $id = input('post.id');
        $res = Lineup::where(['id' => $id])->find();
        //后面的排队信息变化
        $line_up = Lineup::where(['table_id' => $res['table_id'], 'shop_id' => $res['shop_id'], 'ranking' => ['>', $res['ranking']]])->select();
        foreach ($line_up as &$value) {
            if ($value['ranking'] - $res['ranking'] <= 3) {
                $value->ranking = $value['ranking'] - 1;
                $value->save();
            }
        }
        $res->ranking = $res['ranking'] + 3;
        $res->save();
        $this->success('成功');
    }

}